package com.itmk.web.news.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.news.entity.News;
import com.itmk.web.news.entity.NewsPageParm;
import com.itmk.web.news.service.NewsService;
import com.itmk.web.sys_notice.entity.SysNotice;
import com.itmk.web.sys_notice.entity.SysNoticePageParm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    @PreAuthorize("hasAuthority('sys:news:add')")
    @PostMapping("/add")
    public ResultVo add(@RequestBody News news){
        news.setCreateTime(new Date());
        if(newsService.save(news)) {
            return ResultUtils.success("新增成功");
        }
        return ResultUtils.success("新增失败");
    }

    //编辑
    @PreAuthorize("hasAuthority('sys:news:edit')")
    @PutMapping("/edit")
    public ResultVo edit(@RequestBody News news){
        if(newsService.updateById(news)) {
            return ResultUtils.success("编辑成功");
        }
        return ResultUtils.success("编辑失败");

    }

    //删除
    @PreAuthorize("hasAuthority('sys:news:delete')")
    @DeleteMapping("/{id}")
    public ResultVo delete(@PathVariable("id") Long id ){
        if(newsService.removeById(id)) {
            return ResultUtils.success("删除成功");
        }
        return ResultUtils.success("删除失败");


    }

    //列表
    @GetMapping("/list")
    //列表
    public ResultVo list(NewsPageParm parm){
        //构造分页对象
        IPage<News> page = new Page<>(parm.getCurrentPage(),parm.getPageSize());
        //构造查询条件
        QueryWrapper<News> query = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(parm.getTitle())){
            query.lambda().like(News::getTitle,parm.getTitle());
        }

        //排序，新的新出
        query.lambda().orderByDesc(News::getCreateTime);
        IPage<News> list =newsService.page(page,query);
        return ResultUtils.success("查询成功",list);
    }
}
